<?php

class Service_site extends MY_Service
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Model_urls');
        $this->load->model('Model_common');
        $this->load->library('HttpUtil');
        $this->load->library('EmojiUtil');
        $this->load->library('common/CommonEnum');
    }

    public function info()
    {
        $index = (int)$this->getConfigVal(CommonEnum::SITE_INFO_INDEX_CONFIG_ID);
        $limit = (int)$this->getConfigVal(CommonEnum::SITE_INFO_LIMIT_CONFIG_ID);
        $sql = "select * from urls where id > ? AND status = 0 limit ?";
        $list = $this->Model_urls->query($sql, [$index, $limit]);
        if (empty($list)) {
            return false;
        }

        $lastId = $index;
        foreach ($list as $url) {
            $this->_dealSiteInfo($url);
            $lastId = $url['id'];
        }

        $nextIndex = $lastId;
        $this->updateConfigVal(9, $nextIndex);
    }

    public function realUrl()
    {
        $index = (int)$this->getConfigValByKey(CommonEnum::SITE_INFO_REAL_URL_INDEX);
        $limit = (int)$this->getConfigValByKey(CommonEnum::SITE_INFO_REAL_URL_LIMIT);
        $sql = "select * from urls where id > ? AND status = 0 limit ?";
        $list = $this->Model_urls->query($sql, [$index, $limit]);
        if (empty($list)) {
            return false;
        }

        $lastId = $index;
        foreach ($list as $info) {
            $this->_dealRealUrl($info);
            $lastId = $info['id'];
        }

        $nextIndex = $lastId;
        $this->updateConfigValByKey(CommonEnum::SITE_INFO_REAL_URL_INDEX, $nextIndex);
    }

    private function _dealSiteInfo($url)
    {
        $info = $this->_getTDK($url['url']);
        if (!$info) {
            $info = $this->_getSiteInfo($url);
            if (!$info) {
                echo "{$url['id']}：" . $url['url'] . "：未取到关键字。" . PHP_EOL;
                return;
            }
        }

        // 处理标题
        if (!empty($info['title'])) {
            $sql = "UPDATE urls SET title = ? WHERE id = ? and title = '' limit 1";
            $this->Model_common->queryForUpdate($sql, [EmojiUtil::emojiToUtf($info['title']), $url['id']]);
        }

        // 处理备注
        if (!empty($info['remark'])) {
            $sql = "UPDATE urls SET remark = ? WHERE id = ? and remark = '' limit 1";
            $this->Model_common->queryForUpdate($sql, [EmojiUtil::emojiToUtf($info['remark']), $url['id']]);
        }

        // 处理关键词
        if (!empty($info['keywords'])) {
            $sql = "UPDATE urls SET keywords = ? WHERE id = ? and keywords = '' limit 1";
            $this->Model_common->queryForUpdate($sql, [implode(',', $info['keywords']), $url['id']]);
        }

        // 处理关键字关系
        foreach ($info['keywords'] as $key) {
            $key = trim(EmojiUtil::emojiToUtf($key));
            if (empty($key) || strlen($key) > 35) {
                continue;
            }

            $sql = "INSERT INTO keywords(keyword, create_time, update_time, num) values(?, ?, ?, 1) ON DUPLICATE KEY UPDATE update_time = ?, num = num + 1 ";
            $this->Model_common->queryForUpdate($sql, [$key, time(), time(), time()]);

            $this->Model_common->setTable('keywords');
            $keyInfo = $this->Model_common->getByParams(["keyword" => $key]);
            if (empty($keyInfo['id'])) {
                continue;
            }

            $sql = "INSERT INTO url_keywords(url_id, key_id, create_time, update_time) values(?, ?, ?, ?) ON DUPLICATE KEY UPDATE update_time = ? ";
            $this->Model_common->queryForUpdate($sql, [$url['id'], $keyInfo['id'], time(), time(), time()]);
        }

        echo "{$url['id']}：" . $url['url'] . "：取到关键字->" . implode(',', $info['keywords']) . PHP_EOL;
    }

    private function _dealRealUrl($info, $tryTimes = 2)
    {
        if ($tryTimes <= 0) {
            return false;
        }

        $format = json_decode($this->getConfigValByKey(CommonEnum::REAL_URL_FORMAT), TRUE);
        $this->load->service('Service_api');
        $result = $this->Service_api->format(['url' => $info['x_url']], $format);
        $realUrl = $result['url'];
        $tryTimes--;
        if ($realUrl != $info['x_url']) {
            $sql = "UPDATE urls SET url = ?, `show` = 1 WHERE id = ? and url = '' limit 1";
            $this->Model_common->queryForUpdate($sql, [$realUrl, $info['id']]);
            echo "({$info['id']})" . $info['title'] . "：取到真实地址->{$realUrl}" . PHP_EOL;
        } else {
            $this->_dealRealUrl($info, $tryTimes);
        }
    }

    private function _getSiteInfo($url)
    {
        $opts = array(
            'http' => array(
                'method' => "GET",
                'timeout' => 1.5,
            )
        );
        $context = stream_context_create($opts);

        $url['url'] = stripos($url['url'], 'http') === false ? "http:" . $url['url'] : $url['url'];
        $tmpUrl = str_replace("http://", "https://", $url['url']);
        $info = @file_get_contents($tmpUrl, false, $context);
        if (!$info) {
            $tmpUrl = str_replace("https://", "http://", $tmpUrl);
            $info = @file_get_contents($tmpUrl, false, $context);
            if (!$info) {
                return false;
            }
        }

        preg_match('/<title>(.*?)<\/title>/', $info, $title);
        preg_match('/<meta name="description" content="(.*?)"/', $info, $remark);
        preg_match('/<meta name="keywords" content="(.*?)"/', $info, $keywords);

        if (empty($keywords)) {
            return false;
        }

        isset($title[1]) && $title[1] = $this->_decodeUtf8($title[1]);
        isset($remark[1]) && $remark[1] = $this->_decodeUtf8($remark[1]);
        isset($keywords[1]) && $keywords[1] = $this->_decodeUtf8($keywords[1]);

        // 特殊处理
        $tmpKeys = isset($keywords[1]) ? $keywords[1] : "";
        $tmpKeywords = explode(',', $tmpKeys);
        if (stripos($tmpKeys, '，') !== false && count($tmpKeywords) < 2) {
            $tmpKeywords = explode('，', $tmpKeys);
        }

        if (stripos($tmpKeys, ' ') !== false && count($tmpKeywords) < 2) {
            $tmpKeywords = explode(' ', $tmpKeys);
        }

        // 没有keywords存空数组
        return [
            'title' => trim(isset($title[1]) ? $title[1] : $url['title']),
            'remark' => trim(isset($remark[1]) ? $remark[1] : $url['remark']),
            'keywords' => $tmpKeywords
        ];
    }

    private function _getTDK($url)
    {
        $this->load->config('common/url_info');
        $site = $this->config->item('tdk');
        $url = stripos($url, 'http')===false ? "https:" . $url : $url;
        $site['data'] = ['url' => $url];
        $res = HttpUtil::cfg_request_options($site);
        $result = json_decode($res, true);
        if ($result['code'] == 200 && !empty($result['data'])) {
            return [
                'title' => $result['data']['title'],
                'remark' => $result['data']['description'],
                'keywords' => explode(',', $result['data']['keywords'])
            ];
        }
        return false;
    }

    private function _decodeUtf8($info)
    {
        $encode = mb_detect_encoding($info, array('GB2312', 'GBK', 'UTF-8'));
        if ($encode == "GB2312") {
            $info = iconv("GBK", "UTF-8", $info);
        } else if ($encode == "GBK") {
            $info = iconv("GBK", "UTF-8", $info);
        } else if ($encode == "EUC-CN") {
            $info = iconv("GBK", "UTF-8", $info);
        }
        return $info;
    }
}
